package com.advertisementsystem.adservice.service;

import com.advertisementsystem.adservice.entity.Ad;
import com.advertisementsystem.adservice.entity.AdCategory;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.advertisementsystem.adservice.mapper.AdMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
public class AdService {

    private static final Logger logger = LoggerFactory.getLogger(AdService.class);

    @Autowired
    private AdMapper adMapper;

    // 本地存储路径配置
    @Value("${file.upload.local-dir:./uploads}")
    private String localUploadDir;

    // 本地存储URL前缀
    @Value("${file.upload.local-url-prefix:/uploads/}")
    private String localUrlPrefix;

    private FastFileStorageClient storageClient;

    @Autowired(required = false)
    public void setStorageClient(FastFileStorageClient storageClient) {
        this.storageClient = storageClient;
    }

    public List<Ad> findAll() {
        return adMapper.findAll();
    }

    public Ad findById(Integer id) {
        return adMapper.findById(id);
    }

    public int save(Ad ad) {
        if (ad.getId() == null) {
            return adMapper.insert(ad);
        } else {
            return adMapper.update(ad);
        }
    }

    public int delete(Integer id) {
        return adMapper.delete(id);
    }

    public List<AdCategory> findAllCategories() {
        return adMapper.findAllCategories();
    }

    public AdCategory findCategoryById(Integer id) {
        return adMapper.findCategoryById(id);
    }

    public int saveCategory(AdCategory category) {
        if (category.getId() == null) {
            return adMapper.insertCategory(category);
        } else {
            return adMapper.updateCategory(category);
        }
    }

    public int deleteCategory(Integer id) {
        return adMapper.deleteCategory(id);
    }

    public int updateCategory(AdCategory category) {
        return adMapper.updateCategory(category);
    }

    public String uploadImage(MultipartFile file) throws IOException {
        // 首先尝试使用FastDFS上传
        if (storageClient != null) {
            try {
                String fileName = file.getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
                logger.info("文件成功上传到FastDFS: {}", storePath.getFullPath());
                return storePath.getFullPath();
            } catch (Exception e) {
                logger.warn("FastDFS上传失败，尝试本地存储: {}", e.getMessage());
                // 继续执行本地存储
            }
        } else {
            logger.warn("FastDFS客户端未配置，使用本地存储");
        }

        // FastDFS上传失败或未配置，使用本地存储
        return saveToLocal(file);
    }

    private String saveToLocal(MultipartFile file) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(localUploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
            logger.info("创建本地存储目录: {}", uploadPath.toAbsolutePath());
        }

        // 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.contains(".")
                ? originalFileName.substring(originalFileName.lastIndexOf("."))
                : "";
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = uploadPath.resolve(uniqueFileName);
        Files.copy(file.getInputStream(), filePath);
        logger.info("文件已保存到本地: {}", filePath.toAbsolutePath());

        // 返回本地存储的URL（使用配置的前缀）
        return localUrlPrefix + uniqueFileName;
    }

    // 可选：添加文件删除方法
    public boolean deleteFile(String filePath) {
        if (filePath.startsWith(localUrlPrefix)) {
            // 本地文件删除
            String fileName = filePath.substring(localUrlPrefix.length());
            Path fileToDelete = Paths.get(localUploadDir, fileName);
            try {
                return Files.deleteIfExists(fileToDelete);
            } catch (IOException e) {
                logger.error("删除本地文件失败: {}", fileToDelete, e);
                return false;
            }
        } else if (storageClient != null) {
            // FastDFS文件删除
            try {
                storageClient.deleteFile(filePath);
                return true;
            } catch (Exception e) {
                logger.error("删除FastDFS文件失败: {}", filePath, e);
                return false;
            }
        }
        return false;
    }
}